﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using OpenNETCF.Security.Cryptography;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using FFWinMobile.Properties;

namespace FFWinMobile
{
    public partial class frmEntry : Form
    {
        public frmEntry()
        {
            InitializeComponent();
        }
        string entryID = null;
        bool editEntry = false;
        public frmEntry(string id)
        {
            entryID = id;
            InitializeComponent();
        }
        
        public frmEntry(string id, bool edit)
        {
            editEntry = edit;
            entryID = id;
            InitializeComponent();
        }  

        private void frmEntry_Load(object sender, EventArgs e)
        {
            pnlFeeds.Height = (this.Height - 41);
            if (GF.Giris)
            {
                ReadFeed();
            }
            else
            {
                frmLogin frm = new frmLogin();
                DialogResult dr = frm.ShowDialog();
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                if (dr == DialogResult.OK)
                {
                    this.Show();
                    ReadFeed();
                }
                else
                {
                    Application.Exit();
                }
            }
           
        }

        private void ReadFeed()
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            pnlFeeds.Controls.Clear();
            string response;
            
                response = FF.ReadFeed(entryID);
          
            JObject j = JObject.Parse(response);
            JArray entries = (JArray)j["entries"];
            int x = 3, y = 3;
            Rectangle rect = pnlFeeds.ClientRectangle;
            rect.Width -= 20;

            foreach (JObject entry in entries)
            {
                JToken from = entry["from"];
                LinkLabel user = new LinkLabel();
                user.Location = new Point(x, y);
                user.Font = new Font(FontFamily.GenericSansSerif, 10f, FontStyle.Bold);
                user.ForeColor = Color.Black;
                user.Tag = from["id"].Value<string>();
                user.Text = from["name"].Value<string>();
                user.Width = rect.Width;
                user.Height = CFMeasureString.MeasureString(user, user.Text, rect).Height;
                user.Click += new EventHandler(user_Click);
                y += 1;
                y += user.Size.Height;
                pnlFeeds.Controls.Add(user);

                JToken body = entry["rawBody"];
                JToken url = entry["rawLink"];
                LinkLabel linkLabel = new LinkLabel();
                linkLabel.Font = new Font(FontFamily.GenericSansSerif, 9f, FontStyle.Regular);

                linkLabel.Location = new Point(x, y);               
                linkLabel.Text = body.Value<string>();
                linkLabel.Height = CFMeasureString.MeasureString(linkLabel, linkLabel.Text, rect).Height;                
                pnlFeeds.Controls.Add(linkLabel);
                linkLabel.Width = rect.Width;
                y += linkLabel.Size.Height;
                y += 2;

              
                bool deleteLike = false;
                if (entry["likes"] != null)
                {
                    foreach (JToken like in entry["likes"])
                    {
                        JToken likeFromControl = like["from"];
                        {
                            if (GF.UserName == likeFromControl["id"].Value<string>())
                            {
                                deleteLike = true;
                                break;
                            }
                        }
                    }
                }
                if (from["id"].Value<string>() != GF.UserName)
                {
                    Button btnLike = new Button();
                    if (deleteLike)
                        btnLike.Tag = j["id"].Value<string>() + "|delete";
                    else
                        btnLike.Tag = j["id"].Value<string>() + "|add";
                    btnLike.Text = deleteLike ? Properties.Resources.DELETE_LIKE : Properties.Resources.LIKE;

                    btnLike.Width = 115;
                    btnLike.Location = new Point(x, y);
                    btnLike.Click += new EventHandler(btnLike_Click);
                    pnlFeeds.Controls.Add(btnLike);
                    y += (2 + btnLike.Height);
                }

                if (GF.ShowPics)
                {
                    if (entry["thumbnails"] != null)
                    {
                        foreach (JToken pic in entry["thumbnails"])
                        {
                            PictureBox pb = new PictureBox();
                            Image i = GF.DownloadImage(pic["url"].Value<string>());
                            pb.Image = i;

                            int picX = i.Width;
                            if (picX > (pnlFeeds.Width - 13))
                                picX = pnlFeeds.Width - 13;

                            pb.Width = picX;
                            pb.Height = i.Height;
                            pb.SizeMode = PictureBoxSizeMode.StretchImage;

                            pb.Tag = pic["link"].Value<string>();
                            pb.Click += new EventHandler(pb_Click);
                            pb.Location = new Point(x, y);
                            y += (pb.Height + 3);
                            pnlFeeds.Controls.Add(pb);
                        }
                    }
                } 
                y += 2;   
                    JArray comments = (JArray)entry["comments"];
                    if (comments != null)
                    {
                        JToken comment;
                        comment = comments[0];
                        int nameY = y, nameX = x;
                        nameX = 20;
                        while (comment != null)
                        {

                            if (comment["id"] != null)
                            {

                                PictureBox pb = new PictureBox();
                                pb.Image = Properties.Resources.comment1;
                                pb.Size = Properties.Resources.comment1.Size;
                                pb.Location = new Point(x, nameY);
                                pnlFeeds.Controls.Add(pb);

                                JToken commentFrom = comment["from"];
                                Label lblComment = new Label();
                                lblComment.Text = string.Format("{0}", comment["rawBody"].Value<string>());
                                lblComment.Location = new Point(nameX, nameY);
                                lblComment.Font = new Font(FontFamily.GenericSerif, 8f, FontStyle.Regular);
                                lblComment.Width = rect.Width;
                                lblComment.Height = CFMeasureString.MeasureString(lblComment, lblComment.Text, rect).Height;

                                nameY += lblComment.Size.Height + 1;
                                pnlFeeds.Controls.Add(lblComment);

                                LinkLabel lblCommentUser = new LinkLabel();
                                lblCommentUser.Text = commentFrom["name"].Value<string>();
                                lblCommentUser.Tag = commentFrom["id"].Value<string>();
                                lblCommentUser.Click += new EventHandler(lblComment_Click);
                                lblCommentUser.Width = rect.Width - 30;
                                lblCommentUser.TextAlign = ContentAlignment.TopRight;
                                lblCommentUser.Location = new Point(nameX, nameY);
                                pnlFeeds.Controls.Add(lblCommentUser);
                                nameY += lblCommentUser.Size.Height + 1;

                            }                          

                            comment = comment.Next;
                        }
                        y = (nameY + 1);
                    }

                    JArray likes = (JArray)entry["likes"];
                    if (likes != null)
                    {
                        JToken like;
                        like = likes[0];
                        int nameY = y, nameX = x;
                        nameX = 20;
                        Label lbl = new Label();
                        List<string> sb = new List<string>();
                        while (like != null)
                        {
                           
                                JToken likeFrom = like["from"];
                                sb.Add(likeFrom["name"].Value<string>());
                           
                            like = like.Next;
                        }
                        string veriler = string.Join(", ", sb.ToArray()) +" "+ Properties.Resources.LIKED;
                        lbl.Text = veriler;
                        int height = CFMeasureString.MeasureString(lbl, lbl.Text, rect).Height;
                        // y += nameY + 2;
                        PictureBox pbLike = new PictureBox();
                        pbLike.Image = Properties.Resources.smile1;
                        pbLike.Size = Properties.Resources.smile1.Size;
                        pbLike.Location = new Point(x, nameY);
                        pnlFeeds.Controls.Add(pbLike);
                        lbl.Font = new Font(FontFamily.GenericSerif, 8f, FontStyle.Regular);
                        lbl.Width = rect.Width;
                        lbl.Height = height;
                        lbl.Location = new Point(nameX, nameY);
                        pnlFeeds.Controls.Add(lbl);

                        y = (nameY + height + 3);
                    }
                    y += 1;
                    TextBox txtComment = new TextBox();
                    txtComment.Multiline = true;
                    //txtComment.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;                    
                    txtComment.Size = new Size((this.Width-5), 115);
                    txtComment.Location = new Point(x, y);
                    txtComment.Name = "txtComment";
                    
                    pnlFeeds.Controls.Add(txtComment);
                    
                    y += 117;
                   
                    Button btn = new Button();
                    btn.Size = new Size((this.Width - 5), 44);            
                    
                    btn.Tag = entry["id"].Value<string>();
                    btn.Text = Properties.Resources.SEND;
                    btn.Location = new Point(x, y);
                    btn.Click += new EventHandler(btn_Click);
                    pnlFeeds.Controls.Add(btn);

            }
            Cursor.Current = Cursors.Default;
           

        }

        void btnLike_Click(object sender, EventArgs e)
        {
            string tag = ((Button)sender).Tag.ToString();
            string id = tag.Split('|')[0];
            string work = tag.Split('|')[1];
            string response;
            if(work =="add")
            response = FF.LikeEntry(id);
            else
                response = FF.DeleteLike(id);
            if (response != "error")
            {
                ReadFeed();
            }
            else
            {
                MessageBox.Show(Properties.Resources.ERROR_OCCURED);
            }
        }

        void btn_Click(object sender, EventArgs e)
        {
            foreach (Control c in pnlFeeds.Controls)
            {
                TextBox txt = c as TextBox;
                if (txt != null)
                {
                    if(!string.IsNullOrEmpty(txt.Text))
                    {
                        string id = ((Button)sender).Tag.ToString();
                        string response = FF.PostComment(txt.Text, id);
                         if (response != "error")
                         {
                             ReadFeed();
                         }
                         else
                         {
                             MessageBox.Show(Properties.Resources.ERROR_OCCURED);
                         }
                    }
                }
            }
        }
        void pb_Click(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe", pb.Tag.ToString());
            Process.Start(startInfo);
        }

        void lblComment_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;
            frmUserForm frm = new frmUserForm(lbl.Tag.ToString());
            frm.Show();
        }

       

        void user_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;
            frmUserForm frm = new frmUserForm(lbl.Tag.ToString());
            frm.Show();
        }

        private void miRefresh_Click(object sender, EventArgs e)
        {
            ReadFeed();
        }

        private void miBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void miMe_Click(object sender, EventArgs e)
        {
            frmUserForm frm = new frmUserForm("me");
            frm.Show();
        }

        private void miAddFeed_Click(object sender, EventArgs e)
        {
            frmFeed frm = new frmFeed();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                frmUserForm frmUser = new frmUserForm("me");
                frmUser.Show();
            }
        }

        

        private void miSettings_Click(object sender, EventArgs e)
        {
            frmSettings frm = new frmSettings();
            frm.ShowDialog();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            frmAbout frm = new frmAbout();
            frm.Show();
        }

       

    }
}